package com.example.larou.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

public class AliOssUtil {
    //地域节点
    private static final String ENDPOINT = "https://oss-cn-shenzhen.aliyuncs.com";
    private static final String ACCESS_KEY_ID="LTAI5tHU8tpum4831mCTc6cp";
    private static final String ACCESS_KEY_SECRET="PLgIxZjRPGp9fNqEZi7UeMwk8hXeMG";
    // Bucket名称
    private static final String BUCK_NAME = "spingbootc01";
    public static String uploadFile(String objName, InputStream in) throws Exception {
        //存储对象名称
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        // url组成：https://buck名称.区域节点/objName    区域节点 oss-cn-shenzhen.aliyuncs.com
        String url = "https://"+BUCK_NAME+"."+ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+objName;
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCK_NAME,objName,in);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        }catch (ClientException ce){
            System.out.println("Error Message:"+ce.getMessage());
        }finally {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
        return url;
    }
}
